package com.server.interceptor;

import com.server.domain.Code;
import com.server.entity.User;
import com.server.exception.BusinessException;
import com.server.service.UserService;
import com.server.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class ProjectInterceptor implements HandlerInterceptor {
    @Resource
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try{
            String token = request.getHeader("token");
            if(token == null){
                throw new BusinessException("访问失败！请输入认证token！", Code.BUSINESS_AUTH_ERR);
            }
            // 解析token
            Claims tokenClaims = JwtUtils.parseJWT(token);
            System.out.println(tokenClaims);
            String nickname = tokenClaims.get("nickname").toString();
            String password = tokenClaims.get("password").toString();
            // 解析token是否有效
            if(tokenClaims.isEmpty()){
                throw new Exception("认证失败！请输入有效令牌！");
            }else{
                // 令牌有效，允许通过，不去数据库中进行验证
                // 判断token是否存在于数据库中
                List<User> userlist = userService.findUser(password,nickname);
                if(userlist == null || userlist.isEmpty()){
                    throw new Exception("认证失败！当前帐号没有登录");
                }else{
                    return true;
                }
            }
        }catch (Exception e){
            String msg = e.toString().replace("java.lang.Exception: ","");
            msg = msg.replace("com.server.exception.BusinessException: ","");
            throw new BusinessException(msg, Code.BUSINESS_AUTH_ERR);
        }
    }
}
